﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Radiation___IM
{
    public class MessageParser
    {
        private string m_message;

        private MessageType m_type;
        private Hashtable m_parameters;

        public Hashtable Parameters
        {
            get
            {
                return m_parameters;
            }
        }

        public string Message
        {
            get
            {
                return m_message;
            }
        }

        public MessageType type
        {
            get
            {
                return m_type;
            }
        }

        public MessageParser()
        {
            m_parameters = new Hashtable();
        }

        public rvalue parse(string message)
        {
            try
            {
                string[] splitted_message = message.Split(new char[] { ']' }, 2);

                if (splitted_message.Length == 2) // everything is good
                {
                    string parameters = splitted_message[0].Substring(1); // delete the first char which is '['

                    if (parameters.Length > 1000) // parameter abuse
                        return rvalue.MESSAGE_PARAMETERS_TOO_LONG;

                    string[] real_parameters = parameters.Split(';');

                    for (int i = 0; i < real_parameters.Length; i++)
                    {
                        string[] decomposed_param = real_parameters[i].Split(new char[] { '=' }, 2);

                        if (decomposed_param.Length == 2 && !m_parameters.ContainsKey(decomposed_param[0]))
                            m_parameters.Add(decomposed_param[0], decomposed_param[1]);
                        else if (decomposed_param.Length == 2)
                            m_parameters[decomposed_param[0]] = decomposed_param[1];
                    }

                    if (m_parameters.ContainsKey("c") && (string)m_parameters["c"] == "1")
                        this.m_type = MessageType.Command;
                    else
                        this.m_type = MessageType.Text;

                    this.m_message = splitted_message[1];

                    return rvalue.MESSAGE_PARSED;
                }
                else
                {
                    return rvalue.MESSAGE_COULD_NOT_BE_PARSED;
                }
            }
            catch (Exception)
            {
                return rvalue.MESSAGE_COULD_NOT_BE_PARSED;
            }
        }
    }
}
